package com.estronger.shopmanage.utils;

import android.content.Context;
import android.os.Handler;

import com.estronger.shopmanage.base.MyApplication;

/**
 * @author zhusuibo
 **/

public abstract class Toast {
    public static final int LENGTH_SHORT = android.widget.Toast.LENGTH_SHORT;
    public static final int LENGTH_LONG = android.widget.Toast.LENGTH_LONG;

    private static android.widget.Toast toast;
    private static Handler handler = new Handler();

    private static Runnable run = new Runnable() {
        @Override
        public void run() {
            toast.cancel();
        }
    };

    private static void toast(Context ctx, CharSequence msg, int duration) {
        handler.removeCallbacks(run);
        // handler的duration不能直接对应Toast的常量时长，在此针对Toast的常量相应定义时
        switch (duration) {
            case LENGTH_SHORT:// Toast.LENGTH_SHORT值为0，对应的持续时间1000毫秒
                duration = 1500;
                break;
            case LENGTH_LONG:// Toast.LENGTH_LONG值为1，对应的持续时间3000毫秒
                duration = 3500;
                break;
            default:
                break;
        }
        String smsg = msg.toString();
        if (smsg.contains("Connect")&& smsg.contains("Exception")) {
            String serverAddress = MyApplication.getApplication().getSERVER_URL();
            if(!serverAddress.equals("")){
                smsg = "无法连接服务器"+"("+serverAddress+")"+ "，请检测网络状况或联系管理员！";
            }else{
                smsg = "无法连接服务器，请检测网络状况或联系管理员！";
            }
        } else if (smsg.equals("")) {
            smsg = "请求出错，请稍后重试！";
        }

        if (null != toast) {
            toast.setText(smsg);
        } else {
            toast = android.widget.Toast.makeText(ctx, smsg, Toast.LENGTH_LONG);
        }
        handler.postDelayed(run, duration);
        toast.show();
    }

    /**
     * 弹出Toast
     *
     * @param ctx      弹出Toast的上下文
     * @param msg      弹出Toast的消息
     * @param duration 弹出Toast的持续时间
     */
    public static void show(Context ctx, CharSequence msg, int duration)
            throws NullPointerException {
        if (null == ctx) {
            throw new NullPointerException("The ctx is null!");
        }
        if (0 > duration) {
            duration = LENGTH_SHORT;
        }
        toast(ctx, msg, duration);
    }

    /**
     * 弹出Toast
     *
     * @param ctx      弹出Toast的上下文
     * @param resId    弹出Toast的内容的资源ID
     * @param duration 弹出Toast的持续时间
     */
    public static void show(Context ctx, int resId, int duration)
            throws NullPointerException {
        if (null == ctx) {
            throw new NullPointerException("The ctx is null!");
        }
        if (0 > duration) {
            duration = LENGTH_SHORT;
        }
        toast(ctx, ctx.getResources().getString(resId), duration);
    }

}